﻿using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using STP.Models;
using System.Security.Cryptography;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Diagnostics;

namespace STP.Account
{
    public partial class Register : Page
    {
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            
            if (rfv1.IsValid && rfv2.IsValid && rfv3.IsValid && rfv4.IsValid)
            {
                string name = Name.Text;
                string password = Password.Text;
                string email = EmailBox.Text;
                string tel = PhoneBox.Text;
                string sex = "f";
                if (RadioButton1.Checked)
                    sex = "m";
                createUser(name,password,email,tel,sex);
            }
        }

        public void createUser(string name,string password,string email,string tel,string sex)
        {
            DB db = new DB();
            byte[] result = Encoding.Default.GetBytes(password);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            password = BitConverter.ToString(output).Replace("-", "");
            string sql = "select name from users where name='" + name + "'";
            SqlDataReader dr = db.ExceRead(sql);
            if (dr.Read())
            {
                ErrorMessage1.Text = "用户名已存在。";
                dr.Close();
                return;
            }
            dr.Close();
            sql = "exec insertUser '" + name + "','" + password + "','" + email + "','" + tel + "','" + sex + "'";
            db.ExceSql(sql);
            Session["user"] = name;
            if (Session["returnUrl"] != null)
            {
                string url = Session["returnUrl"].ToString().Trim();
                Session["returnUrl"] = null;
                Response.Redirect("~/index");//有问题：跳转不过去
            }
            else
            {
                Response.Redirect("~/index");
            }
        }
    }
}